package me.jiatao.paging2.network

import android.util.Log
import kotlinx.coroutines.*
import me.jiatao.paging2.network.retrofit.HttpResult
import me.jiatao.paging2.network.retrofit.RetrofitClient
import me.jiatao.paging2.network.retrofit.apiCall
import me.jiatao.paging2.pojo.ProjectPage

class HttpRepository private constructor() {
    companion object {
        private val scope = CoroutineScope(Dispatchers.IO)
        /**
         * 统一处理错误信息等逻辑
         */
        private fun <T> handlerHttpResponse(httpResult: HttpResult<T>): T? {
            if (httpResult.code == 0) {
                return httpResult.data
            }
            Log.i("HttpRepository", "错误信息--->${httpResult.message}")
            return null
        }

        suspend fun getProjectList(pageIndex: Int): ProjectPage? {
            return scope.async {
                println("getProjectList----------> ${Thread.currentThread().name}")
                val dataList = apiCall {
                    RetrofitClient.wanAndroidApi.getProjectList(pageIndex)
                }
                val data = handlerHttpResponse(dataList)
                if (data != null) {
                    return@async data
                }
                cancel()
                return@async null
            }.await()
        }
    }
}